package com.likai.authority.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.likai.authority.dao.UserMapper;
import com.likai.authority.pojo.User;
import com.likai.authority.service.IUserService;
import com.likai.authority.util.IdUtil;
import com.likai.authority.util.Md5;

@Service("userService")
public class UserServiceImpl implements IUserService {
	
	@Autowired
	private UserMapper userMapper;

	@Transactional(readOnly=true)
	public User login(User po) {
		po.setPassword(Md5.getMD5(po.getPassword()));
		return userMapper.selectByUserNameAndPassword(po);
	}

	@Transactional
	public int updatePassword(User po) {
		po.setPassword(Md5.getMD5(po.getPassword()));
		return userMapper.updateByPrimaryKeySelective(po);
	}

	@Transactional(readOnly=true)
	public List<User> findListAndRoleName(User po) {
		return userMapper.selectListAndRoleName(po) ;
	}

	@Transactional
	public int updayeUser(User po) {
		boolean flag = false ;
		String userid = po.getUserid() ;
		if(userid == null) {
			po.setUserid(IdUtil.uuid());
			po.setPassword(Md5.getMD5(po.getPassword()));
			if(userMapper.insertSelective(po) == 1) {
				flag = true ;
			}
		}else {
			if(userMapper.updateByPrimaryKeySelective(po) == 1) {
				flag = true ;
			}
		}
		if(flag) {
			return 1 ;
		} else {
			return 0 ;
		}
	}

	@Transactional(readOnly=true)
	public User findUserByUsername(String username) {
		return userMapper.selectUserByUsername(username);
	}

	@Transactional(readOnly=true)
	public User findUserByUserid(String id) {
		return userMapper.selectByPrimaryKey(id);
	}

	@Transactional
	public int removeUser(String[] ids) {
		boolean flag = false ;
		for (String id : ids) {
			if(userMapper.deleteByPrimaryKey(id) == 1) {
				flag = true ;
			}
		}
		if(flag) {
			return 1 ;
		} else {
			return 0 ;
		}
	}

	public List<User> findByRoleId(String roleid) {
		return userMapper.selectByRoleId(roleid);
	}

}
